<template>
  <div class="profile-page">

    <div class="user-info">
      <div class="container">
        <div class="row">

          <div class="col-xs-12 col-md-10 offset-md-1">
            <img :src="profile.image" class="user-img" />
            <h4>{{ profile.username }}</h4>
            <p>{{ profile.bio }}</p>

            <template v-if="isSelf">
              <nuxt-link
                class="btn btn-sm btn-outline-secondary action-btn"
                :to="{
                  name: 'settings',
                }">
                <i class="ion-gear-a"></i> Edit Profile Settings
              </nuxt-link>
            </template>

            <template v-else>
              <button class="btn btn-sm btn-outline-secondary action-btn">
                <i class="ion-plus-round"></i>
                &nbsp;
                Follow {{ profile.username }} 
              </button>
            </template>

          </div>

        </div>
      </div>
    </div>

    <div class="container">
      <div class="row">

        <div class="col-xs-12 col-md-10 offset-md-1">
          <div class="articles-toggle">
            <ul class="nav nav-pills outline-active">
              <li class="nav-item">
                <nuxt-link
                  exact
                  class="nav-link"
                  :class="{ active: tab === 'my_articles' }"
                  :to="{
                    name: 'profile',
                    params: { username: profile.username },
                    query: { tab: 'my_articles' }
                  }">My Articles</nuxt-link>
              </li>
              <li class="nav-item">
                <nuxt-link
                  exact
                  class="nav-link"
                  :class="{ active: tab === 'fav_articles' }"
                  :to="{
                    name: 'profile',
                    params: { username: profile.username },
                    query: { tab: 'fav_articles' }
                  }">Favorited Articles</nuxt-link>
              </li>
            </ul>
          </div>

          <div
            v-for="article in articleList"
            :key="article.slug"
            class="article-preview">
            <div class="article-meta">
              <nuxt-link 
                :to="{
                  name: 'profile',
                  params: { username: article.author.username }
                }">
                <img :src="article.author.image" />
              </nuxt-link>
              <div class="info">
                <nuxt-link
                  class="author"
                  :to="{
                    name: 'profile',
                    params: { username: article.author.username }
                  }">
                  {{ article.author.username }}
                </nuxt-link>
                <span class="date">{{ article.createAt | date('MMM DD, YYYY') }}</span>
              </div>
              <button
                class="btn btn-outline-primary btn-sm pull-xs-right"
                :class="{ active: article.favorited }"
                :disabled="article.favoriteDisabled"
                @click="toggleFavorite(article)">
                <i class="ion-heart"></i> {{ article.favoritesCount }}
              </button>
            </div>
            <nuxt-link
              class="preview-link"
              :to="{
                name: 'article',
                params: { slug: article.slug }
              }">
              <h1>{{ article.title }}</h1>
              <p>{{ article.description }}</p>
              <span>Read more...</span>
              <ul class="tag-list">
                <li
                  class="tag-default tag-pill tag-outline"
                  v-for="tag in article.tagList"
                  :key="tag">{{ tag }}</li>
              </ul>
            </nuxt-link>
          </div>

          <ul class="pagination">
            <li
              class="page-item"
              :class="{
                active: item === page
              }"
              v-for="item in pageCount" :key="item">
              <nuxt-link
                class="page-link"
                :to="{
                  name: 'profile',
                  params: { username: profile.username },
                  query: {
                    page: item,
                    tab: tab
                  }
                }">{{ item }}</nuxt-link>
            </li>
          </ul>
        </div>

      </div>
    </div>

  </div>
</template>

<script>
import { mapState } from 'vuex'

import {
  getProfile,
  getArticleList,
  addFavorite,
  deleteFavorite
} from '@/api'

export default {
  name: 'ProfilePage',
  middleware: 'auth',
  watchQuery: ['username', 'page', 'tab'],
  head () {
    return {
      title: `@${this.profile.username} - RealWorld`
    }
  },
  async asyncData ({ params, query }) {
    const limit = 5,
          page = Number(query.page || 1),
          tab = query.tab || 'my_articles'

    const articleQuery = {
      limit: limit,
      offset: (page - 1) * limit
    }
    // 请求参数
    if (tab === 'my_articles') {
      articleQuery.author = params.username
    } else if (tab === '') {
      articleQuery.favorited = params.username
    }

    const [ profileRes, articleListRes ] = await Promise.all([
      getProfile(params.username),
      getArticleList(articleQuery)
    ])

    const { articles, articlesCount } = articleListRes.data
    articles.forEach(item => item.favoriteDisabled = false)

    return {
      tab,
      page,
      limit,
      profile: profileRes.data.profile,
      articleList: articles,
      articlesCount: articlesCount
    }
  },
  data () {
    return {
      favArticles: [],
    }
  },
  computed: {
    ...mapState(['user']),
    isSelf () {
      if (!this.user) return false
      return this.user.username === this.profile.username
    },
    pageCount () {
      return Math.ceil(this.articlesCount / this.limit)
    }
  },
  methods: {
    async toggleFavorite (article) {
      article.favoriteDisabled = true
      if (article.favorited) {
        // 取消点赞
        await deleteFavorite(article.slug)
        article.favorited = false
        article.favoritesCount += -1
      } else {
        // 添加点赞
        await addFavorite(article.slug)
        article.favorited = true
        article.favoritesCount += 1
      }
      article.favoriteDisabled = false
    }
  }
}
</script>
